<!--个人信息-->
<script setup>
import {ref, onMounted} from 'vue';
import {message} from 'ant-design-vue';
import {UserOutlined} from '@ant-design/icons-vue';
import axios from 'axios';

const activeKey = ref('1');
const avatarUrl = ref('');
const fileInput = ref(null);
const userInfo = ref({
  username: '',
  nickName: '',
  gender: '',
  phone: '',
  avatar: ''
});

const userInfoTemp = ref({
  username: '',
  nickName: '',
  gender: '',
  phone: '',
  avatar: ''
});

const editingField = ref(''); // 当前正在编辑的字段

// 添加临时编辑值
const editValue = ref('');

const showVerifyCode = ref(false);
const verifyCode = ref('');
const countdown = ref(0);

// 获取用户信息
const getUserInfo = async () => {
  try {
    const token = localStorage.getItem("access-token");
    const response = await axios.get(`${window.link}/user/info`, {
      headers: {
        "access-token": token
      }
    });
    console.log(response);

    if (response.data.code === 200) {
      userInfo.value = response.data.data;
      // 如果有头像URL，也设置头像
      if (response.data.data.avatar) {
        avatarUrl.value = response.data.data.avatar;
      }
    } else {
      message.error("获取用户信息失败");
    }
  } catch (error) {
    console.error("获取用户信息失败", error);
    message.error("获取用户信息失败");
  }
};

// 在组件挂载时获取用户信息
onMounted(() => {
  getUserInfo();
});

const handleUpload = async () => {
  // 触发隐藏的文件输入框
  fileInput.value.click();
};

const onFileChange = async (e) => {
  const target = e.target;
  const file = target.files?.[0];

  if (file) {
    if (!['image/jpeg', 'image/png'].includes(file.type)) {
      message.error('请上传 jpg 或 png 格式的图片');
      return;
    }

    // 创建 FormData 对象用于文件上传
    const formData = new FormData();
    formData.append('files', file);

    try {
      const token = localStorage.getItem("access-token");
      const response = await axios.post(`${window.link}/user/file/upload`, formData, {
        headers: {
          "access-token": token,
          "Content-Type": "multipart/form-data"
        }
      });

      console.log(response);
      if (response.data.code === 200) {
        // 更新头像URL
        avatarUrl.value = URL.createObjectURL(file);
        userInfo.value.avatar = response.data.data[0];
        console.log(userInfo.value.avatar);
        editValue.value = response.data.data[0];
        submitEdit('avatar');
      } else {
        message.error(response.data.message || "上传失败");
      }
    } catch (error) {
      console.error("上传失败", error);
      message.error("上传失败，请稍后重试");
    }

    // 清空文件输入框，允许重复上传相同文件
    target.value = '';
  }
};

// 修改开始编辑函数
const startEdit = (field) => {
  editingField.value = field;
  // 将当前值赋给临时编辑值
  editValue.value = userInfo.value[field];
  // 如果是修改手机号，显示验证码输入框
  if (field === 'phone') {
    showVerifyCode.value = true;
  }
};

// 修改取消编辑函数
const cancelEdit = () => {
  editingField.value = '';
  editValue.value = '';
  showVerifyCode.value = false;
  verifyCode.value = '';
};

// 发送验证码
const handleSendCode = async () => {
  try {
    const token = localStorage.getItem("access-token");
    const response = await axios.get(`${window.link}/login/getCode?phone=${editValue.value}`,
        {
          headers: {
            "access-token": token
          }
        });
    message.success('验证码已发送');
  } catch (error) {
    console.error("发送验证码失败", error);
    message.error("发送验证码失败");
  }
};

// 修改提交编辑函数
const submitEdit = async (type) => {
  try {
    // 如果是修改手机号，需要验证验证码
    if (type === 'phone') {
      if (!verifyCode.value) {
        message.error('请输入验证码');
        return;
      }
    }

    userInfoTemp.value[type] = editValue.value;
    const data = JSON.stringify(userInfoTemp.value);
    const token = localStorage.getItem("access-token");
    const response = await axios.put(`${window.link}/user/info`, data, {
      headers: {
        "Content-Type": "application/json",
        "access-token": token
      }
    });

    if (response.data.code === 200) {
      message.success("修改" + response.data.message);
      // 更新成功后，将临时值赋给实际值
      userInfo.value[type] = userInfoTemp.value[type];
      userInfoTemp.value[type] = '';
      // 退出编辑状态
      cancelEdit();
    } else {
      message.error(response.data.message || "修改失败");
    }
  } catch (error) {
    console.error("修改失败", error);
    message.error("修改失败，请稍后重试");
  }
};

// 添加性别格式化函数
const formatGender = (gender) => {
  switch (gender) {
    case '0':
    case 0:
      return '男';
    case '1':
    case 1:
      return '女';
    case '2':
    case 2:
    default:
      return '未知';
  }
};

</script>
<template>
  <div class="min-h-screen bg-gray-50">
    <div class="w-[1400px] mx-auto py-8 px-4">
      <div class="bg-white rounded-lg shadow-sm p-6">
        <h1 class="text-2xl font-medium mb-8">个人资料</h1>

        <div class="bg-white rounded-lg shadow-sm p-6 mb-8">
          <div class="flex gap-4 mb-6">
            <a-tabs v-model:activeKey="activeKey" class="w-full">
              <a-tab-pane key="1" tab="本地上传"></a-tab-pane>
            </a-tabs>
          </div>

          <div class="flex gap-8 mb-8">
            <div class="w-[200px]">
              <div class="w-[200px] h-[200px] rounded-full bg-gray-100 overflow-hidden mb-4">
                <img v-if="avatarUrl" :src="userInfo.avatar" class="w-full h-full object-cover" alt="avatar"/>
                <div v-else class="w-full h-full flex items-center justify-center text-gray-400">
                  <UserOutlined style="font-size: 64px"/>
                </div>
              </div>
              <a-button type="primary" class="w-full !rounded-button" @click="handleUpload">
                上传头像
              </a-button>
              <input ref="fileInput" type="file" class="hidden" accept="image/*" @change="onFileChange"/>
            </div>

            <div class="flex-1">
              <div class="text-gray-600 mb-4">圆形头像预览</div>
              <div class="text-gray-500 text-sm mb-2">图片格式：jpg png</div>
              <div class="text-gray-500 text-sm">最适尺寸：200*200px</div>
            </div>
          </div>

          <div class="border-t pt-8">
            <h2 class="text-lg font-medium mb-6">修改个人资料</h2>

            <div class="space-y-6">
              <!-- 用户名 -->
              <div class="flex items-center">
                <span class="w-20 text-gray-600">用户名：</span>
                <template v-if="editingField !== 'username'">
                  <span class="text-gray-800 mr-4">{{ userInfo.username }}</span>
                  <a-button
                      type="link"
                      class="!rounded-button text-orange-500 hover:text-orange-600"
                      @click="startEdit('username')"
                  >
                    修改
                  </a-button>
                </template>
                <template v-else>
                  <a-input
                      v-model:value="editValue"
                      class="!w-[200px] mr-4"
                      placeholder="请输入用户名"
                  />
                  <a-button
                      type="link"
                      class="!rounded-button text-orange-500 hover:text-orange-600"
                      @click="submitEdit('username')"
                  >
                    提交
                  </a-button>
                  <a-button
                      type="link"
                      class="!rounded-button text-gray-500 hover:text-gray-600"
                      @click="cancelEdit"
                  >
                    取消
                  </a-button>
                </template>
              </div>

              <!-- 昵称 -->
              <div class="flex items-center">
                <span class="w-20 text-gray-600">昵称：</span>
                <template v-if="editingField !== 'nickName'">
                  <span class="text-gray-800 mr-4">{{ userInfo.nickName }}</span>
                  <a-button
                      type="link"
                      class="!rounded-button text-orange-500 hover:text-orange-600"
                      @click="startEdit('nickName')"
                  >
                    修改
                  </a-button>
                </template>
                <template v-else>
                  <a-input
                      v-model:value="editValue"
                      class="!w-[200px] mr-4"
                      placeholder="请输入昵称"
                  />
                  <a-button
                      type="link"
                      class="!rounded-button text-orange-500 hover:text-orange-600"
                      @click="submitEdit('nickName')"
                  >
                    提交
                  </a-button>
                  <a-button
                      type="link"
                      class="!rounded-button text-gray-500 hover:text-gray-600"
                      @click="cancelEdit"
                  >
                    取消
                  </a-button>
                </template>
              </div>

              <!-- 性别 -->
              <div class="flex items-center">
                <span class="w-20 text-gray-600">性别：</span>
                <template v-if="editingField !== 'gender'">
                  <span class="text-gray-800 mr-4">{{ formatGender(userInfo.gender) }}</span>
                  <a-button
                      type="link"
                      class="!rounded-button text-orange-500 hover:text-orange-600"
                      @click="startEdit('gender')"
                  >
                    修改
                  </a-button>
                </template>
                <template v-else>
                  <a-select
                      v-model:value="editValue"
                      class="!w-[200px] mr-4"
                      placeholder="请选择性别"
                  >
                    <a-select-option value="0">男</a-select-option>
                    <a-select-option value="1">女</a-select-option>
                    <a-select-option value="2">未知</a-select-option>
                  </a-select>
                  <a-button
                      type="link"
                      class="!rounded-button text-orange-500 hover:text-orange-600"
                      @click="submitEdit('gender')"
                  >
                    提交
                  </a-button>
                  <a-button
                      type="link"
                      class="!rounded-button text-gray-500 hover:text-gray-600"
                      @click="cancelEdit"
                  >
                    取消
                  </a-button>
                </template>
              </div>

              <!-- 手机号 -->
              <div class="flex items-start">
                <template v-if="editingField !== 'phone'">
                  <span class="w-20 h-[28px] text-gray-600 flex items-center">手机号：</span>
                  <div class="flex items-center">
                    <span class="text-gray-800 mr-4">{{ userInfo.phone }}</span>
                    <a-button
                        type="link"
                        class="!rounded-button text-orange-500 hover:text-orange-600"
                        @click="startEdit('phone')"
                    >
                      修改
                    </a-button>
                  </div>
                </template>
                <template v-else>
                  <span class="w-20 h-[40px] text-gray-600 flex items-center">手机号：</span>
                  <div class="flex flex-col gap-4">
                    <div class="flex items-center">
                      <a-input
                          v-model:value="editValue"
                          class="!w-[200px] h-[40px] mr-4"
                          placeholder="请输入手机号"
                      />
                    </div>

                    <!-- 验证码输入框 -->
                    <div v-if="showVerifyCode">
                      <a-input
                          v-model:value="verifyCode"
                          class="!w-[200px] h-[40px]"
                          placeholder="请输入验证码"
                      >
                        <template #suffix>
                          <a-button
                              type="link"
                              class="!rounded-button text-orange-500 hover:text-orange-600"
                              @click="handleSendCode"
                          >
                            获取验证码
                          </a-button>
                        </template>
                      </a-input>
                    </div>

                    <div class="flex items-center">
                      <a-button
                          type="link"
                          class="!rounded-button text-orange-500 hover:text-orange-600"
                          @click="submitEdit('phone')"
                      >
                        提交
                      </a-button>
                      <a-button
                          type="link"
                          class="!rounded-button text-gray-500 hover:text-gray-600"
                          @click="cancelEdit"
                      >
                        取消
                      </a-button>
                    </div>
                  </div>
                </template>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>


<style scoped>
:deep(.ant-tabs-nav::before) {
  border-bottom: none !important;
}

:deep(.ant-tabs-tab) {
  padding: 8px 0;
  margin: 0 32px 0 0;
  font-size: 16px;
}

:deep(.ant-tabs-tab-active .ant-tabs-tab-btn) {
  color: #ff4d4f !important;
}

:deep(.ant-tabs-ink-bar) {
  background: #ff4d4f !important;
}
</style>

